var phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;

$('#exampleModal').on('show.bs.modal', function (event) {

  var button = $(event.relatedTarget); // Button that triggered the modal

  var recipient = button.data('whatever'); // Extract info from data-* attributes

  var modal = $(this);

  modal.find('.loadlbBackground').attr('src','');

  modal.find('#message-text').val('');

  modal.find('input[name=lbt]').val('');
  $('input:radio[value="shop"]').prop("checked",true).trigger("change");
  $('.confirmlbt').unbind('click');
  if(recipient==0){
  	editText(modal,1);

  	$('.close-modal').removeClass('close-modal-del').unbind('click');

  	$('.confirmlbt').removeClass('editlbt').addClass('addlbt');

  	$('input[name="action"]').val(1);

  	$('input[name="broadcast_id"]').val(0);

  	$('input[name="shop_id"]').val(0);

	$('.addlbt').click(function(){
		editlbt('insert');
	});
  }else{
  	var shopid = recipient.split('/')[0];

  	var lbt_id = recipient.split('/')[1];

  	editText(modal,0);

  	modal.find('.loadlbBackground').attr('src',button.find('img').attr('src'));

  	var type = button.data('type');

  	if(type==1){
  		searchShop('shop_id',shopid);
  	}else if(type==2){
  		modal.find('#message-text').val(button.data('url'));
  		$('input:radio[value="url"]').prop("checked",true).trigger("change");
  	}

  	$('.confirmlbt').removeClass('addlbt').addClass('editlbt');

  	$('.close-modal').addClass('close-modal-del');

  	$('.close-modal-del').click(delLbt);

  	$('input[name="action"]').val(0);

  	$('input[name="broadcast_id"]').val(lbt_id);

  	$('.editlbt').click(function(){
		editlbt('edit');
	});
  }

  if(!$('.shop-info').hasClass('hide')){
	$('.shop-info').addClass('hide');
  }

  if(!$('.shop-info-name').hasClass('label-info')){
  	$('.shop-info-name').removeClass('label-error').addClass('label-info');
  }
  var v = $('input:radio[name="targettype"]:checked').val();
  if(v=='url'){
  	modal.find('#message-text').unbind('input propertychange');
  }else if(v=='shop'){
  	modal.find('#message-text').unbind('input propertychange');
   	modal.find('#message-text').bind('input propertychange',shopChange);
  }

  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  modal.find('.modal-body input[name="extractid"]').val(recipient);

});

function shopChange(){
	var v = $(this).val();
	if(phoneReg.test(v)){
		searchShop('tel',v);
	}else if(v==''){
		$('.shop-info').addClass('hide');
	}
}

$('input:radio[name="targettype"]').change(function(){
	var v = $('input:radio[name="targettype"]:checked').val();
	if(v=='url'){
		checkUrl();
	}else if(v=='shop'){
		checkShop();
	}else if(v=='show'){
		checkShow();
	}
});
function checkShop(){
	$('.hiddblock').css('display','block');
	$('.shop-phone').html('推荐店铺:');
	$('.searchshop').attr('placeholder','填写店铺的账号，手机号');
	$('#message-text').val('');
	$('#message-text').unbind('input propertychange');
	$('#message-text').bind('input propertychange',shopChange);
}
function checkUrl(){
	$('.hiddblock').css('display','block');
	$('.shop-phone').html('跳转地址:');
	$('.searchshop').attr('placeholder','跳转地址 http[s]://www.jiashilexiang.com');
	$('#message-text').unbind('input propertychange');
}

function checkShow(){
	$('.hiddblock').css('display','none');
}

// 删除轮播图
function delLbt() {
	swal({
	  title: '您确定删除该轮播图吗？', 
	  text: '删除后将不展示在APP首页！', 
	  type: 'question',
	  showCancelButton: true, 
	  confirmButtonColor: '#3085d6',
	  cancelButtonColor: '#d33',
	  confirmButtonText: '确定', 
	  cancelButtonText: '取消',
	  confirmButtonClass: 'btn btn-success',
	  cancelButtonClass: 'btn btn-danger',
	  buttonsStyling: true
	}).then(function(al) {
		if(al.value){
			var lbt_id = $('input[name="broadcast_id"]').val();
			$.post('/broadcastDel',{broadcast_id:lbt_id},function(response){
				if(response.success){
					setTimeout(function(){
						location.href = location.href;
					},2000);
					toastr.success(response.message);
				}else{
					toastr.error(response.message);
				}
			});
		}
	});
	
}

/**
 * 修改添加轮播图
 */
function editlbt(a) {
	var formData = {};

	formData.dataType = 'json';

	formData.beforeSubmit = function (formData, jqForm, options){
		console.log(formData);
		var phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
		var targettype = $('input:radio[name="targettype"]:checked').val();
		if(!phoneReg.test(formData[1].value)&&targettype=='shop'){
			toastr.warning('账号格式不正确，要求为11位手机号');
			return false;
		}
		if(a=='insert'){
			if(formData[2].value==''){
					toastr.warning('请上传图片！');
					return false;
				}
		}
			if(a=='edit'){
				if(formData[5].value==0){
					toastr.warning('ID不能为空！');
					return false;
				}

				if(formData[6].value==''){
					toastr.warning('参数不正确');
					return false;
				}
				
				if(formData[3].value==0&&targettype=='shop'){
					toastr.warning('店铺ID不能为空！');
					return false;
				}
			}
		$('.confirmlbt').attr('disabled','disabled');
	};
	formData.success = function(response){
		$('.confirmlbt').removeAttr('disabled');
		if(response.success){
			setTimeout(function(){
				location.href = location.href;
			},2000);
			toastr.success(response.message);
		}else{
			toastr.error(response.message);
		}
	};

	ajaxForm_('#lbtform',formData);
}

$('.item').eq(0).addClass('active');

$('.item_active').eq(0).addClass('active');


function editText(modal,i){

	var t1 = ['删除该图','取消'];

	var t2 = ['确认更改','确认添加'];

	var t3 = ['btn-danger','btn-default'];

	modal.find('.modal-footer .btn-default').removeClass('btn-default').addClass(t3[i]).html(t1[i]);

  	modal.find('.modal-footer .btn-danger').removeClass('btn-danger').addClass(t3[i]).html(t1[i]);

  	modal.find('.modal-footer .confirmlbt').html(t2[i]);

}


function searchShop(k,v) {

	var data = {};

	if(k=='tel'){
		data.tel = v;
	}else{
		data.shop_id = v;
	}

	$.post('/search-shoptel',data,function(response){

		if(response.success){

			if(k=='tel'){
				$('.shop-info-name').html(response.data.shop_name).removeClass('label-info').addClass('label-danger');
			}else{
				$('.shop-info-name').html(response.data.shop_name).removeClass('label-danger').addClass('label-info');
			}
			$('input[name="shop_name"]').val(response.data.shop_name);

			$('.shop-info-address').html(response.data.shop_address);

			$('input[name="shop_id"]').val(response.data.shop_id);

			$('.shop-info').removeClass('hide');

		}else{
			toastr.options.positionClass = 'toast-top-right';
			toastr.error('没有查询到属于该手机号的店铺！');
		}

	},'json');

}


toastr.options.positionClass = 'toast-top-center';

$('.inserttoutiao').click(function(){

	var inp = $('input[name="model_toutiao"]').clone(true);

	if(inp.hasClass('copy_modemj2')){

	}
	inp.attr('name','toutiaocontent[]').removeClass('hide');

	inp.val('');

	$('.toutiao').append(inp);

	$('input[name="toutiaocontent[]"]:last').focus();

});
$('.inserttoutiao2').click(function(){

	var inp = $('.copy_modemj').clone(true);
	var inp2 = $('.copy_modemj2').clone(true);
	
	inp.attr('name','juzi[]').removeClass('hide').removeClass('copy_modemj');
	inp2.attr('name','zuozhe[]').removeClass('hide').removeClass('copy_modemj2');

	inp.val('');
	inp2.val('');

	$('.toutiao').append(inp);
	$('.toutiao').append(inp2);

	$('input[name="juzi[]"]:last').focus();
	$('input[name="zuozhe[]"]:last').focus();

});
$('.toutiaocontent').focus(function(){

	var this_ = $(this);

	$(document).keydown(function(event){

		var ino = $('.toutiaocontent');

		var len = this_.val();

		if(event.keyCode==8){

			if(len.length==0&&ino.length>1){

				this_.prev().focus();

				this_.remove();

				return false;

			}

		}

		if(event.keyCode==13 && !event.ctrlKey){
			$('.inserttoutiao').trigger('click');
		}

	});

});


$('.toutiaocontent').blur(function(){

	$(document).unbind('keydown');

});

var huodongSendParam = {
	'dataType':'json',
	'beforeSubmit':toutiaoBefore,
	'success':toutiaoResponse,
	'error':toutiaoError,
};

var SendParam = {
	'dataType':'json',
	'beforeSubmit':toutiaoBefore,
	'success':toutiaoResponse,
	'error':toutiaoError,
};

function toutiaoBefore(formData, jqForm, options){
	
}

function toutiaoResponse(response) {
	if(response.success){
		toastr.success(response.message);
	}else{
		toastr.error('修改失败，请联系开发人员！');
	}
}

function toutiaoError(XMLHttpRequest, textStatus, errorThrown) {

	if(XMLHttpRequest.status==422){

		var RegError = XMLHttpRequest.responseJSON.errors;

		for(var o in RegError){

			for (var i = 0; i < RegError[o].length; i++) {

				toastr.error(RegError[o][i]);

			}

		}

	}

}

ajaxForm_('#toutiaoFrom', SendParam);
ajaxForm_('#huodongForm', huodongSendParam);


$('input[type=file][name=lbt],input[type=file][name=fanka]').change(function(e){

	var files = e.target.files;

	var v = $(this).val();

	var reader = new window.FileReader();

	reader.readAsDataURL(files[0]);
	var this_ = $(this);
	//异步加载文件成功
    reader.onload = function(e){
       // reader.result 表示图片地址
       $(this_).prev().attr('src',reader.result);
    }

});


document.onkeydown = function(event) {

    var target, code, tag;

    if (!event) {  
        event = window.event; //针对ie浏览器
        target = event.srcElement;  
        code = event.keyCode;  
        if (code == 13) {  
            tag = target.tagName;  
            if (tag == "TEXTAREA") { return true; }
            else { return false; }  
        }  
    }  
    else {  
        target = event.target; //针对遵循w3c标准的浏览器，如Firefox
        code = event.keyCode;
        if (code == 13) {
            tag = target.tagName;
            if (tag == "INPUT") { return false; }
            else { return true; }
        }  
    }  
};

$('.savedefaultimg').click(function(){
	
});